import React, { createContext,useContext, useEffect } from 'react';
import ReactDOM from 'react-dom/client';
import {message} from 'antd';
import './index.css';

import {
    RouterProvider,
    useLocation,
} from "react-router-dom";
import './index.css';
import router from './router/router-index';
import MicorAppContext from './context/micro-app-context';


// 定义一个新的类型，包含 Window 和自定义属性
type WindowWithCustomVars = Window & {
    __POWERED_BY_QIANKUN__: {
        onGlobalStateChange:(params:((state:any)=>void))=>void,
        setGlobalState:(params:any)=>void
    };
};
  
// 声明 window 为新的类型
declare let window: WindowWithCustomVars;



const App = ()=>{
    const micorApp:any = useContext(MicorAppContext);

    useEffect(()=>{
        if (window.__POWERED_BY_QIANKUN__) {
            micorApp.onGlobalStateChange((state:any,prev:any)=>{
                if(state.from === 'mainApp'){
                    message.info(`子应用收到来自主应用的消息 message = ${state.message}--state = ${JSON.stringify(state.state)}`);
                }
            });
        }
    },[])
    
    return <React.StrictMode>
        <RouterProvider router={router} />
    </React.StrictMode>
}

function render(props:any) {
    const { container,onGlobalStateChange, setGlobalState} = props;

    ReactDOM.createRoot(container ? container.querySelector('#sub-one-root') : document.querySelector('#sub-one-root')).render(
    <MicorAppContext.Provider value={{onGlobalStateChange, setGlobalState}}>
        <App />
    </MicorAppContext.Provider>);
}
  

if (!window.__POWERED_BY_QIANKUN__) {
    render({});
}


export async function bootstrap() {
    console.log('[react18] react app bootstraped');
}

export async function mount(props:any) {
    render(props);
}

export async function unmount(props:any) {
    const { container } = props;
    message.info('子应用已卸载');
    console.log('子应用已卸载');
}